package br.com.novagalvao.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import br.com.novagalvao.beans.Cliente;
import br.com.novagalvao.services.ClienteServices;


@Controller
@RequestMapping(value = "/cliente")
public class ClienteController {
	
	private static final String REDIRECT_LISTAR = "redirect:/cliente/listar";
	private static final String CONTEXT_PAGE = "pages";
	
	@Autowired
	private ClienteServices clienteServices;
	
	@RequestMapping(value = "/novo")
	public String novo(){
		return CONTEXT_PAGE+"/cliente/cliente";
	}
	
	
	@RequestMapping(value = "/salvar", method = RequestMethod.POST)
	public String salvar(Cliente cliente){
		clienteServices.salvar(cliente);
		return REDIRECT_LISTAR;
	}
	
	
	@RequestMapping(value = "/listar")
	public ModelAndView lista(){
		
		ModelAndView mav = new ModelAndView(CONTEXT_PAGE+"/cliente/lista");
		List<Cliente> clientes = clienteServices.listar();
		mav.addObject(clientes);
		
		return mav;
	}
	
	@RequestMapping(value = "/editar/{id}")
	public ModelAndView editar(@PathVariable int id){
		
		ModelAndView mav = new ModelAndView(CONTEXT_PAGE+"/cliente/cliente");
		Cliente cliente = clienteServices.findById(id);
		mav.addObject(cliente);
		
		return mav;
		
	}
	
	@RequestMapping(value = "/excluir/{id}", method = RequestMethod.GET)
	public String excluir(@PathVariable int id){
		clienteServices.excluir(id);
		return REDIRECT_LISTAR;
	}
	
	@RequestMapping(value = "/inativarAtivar/{id}", method = RequestMethod.GET)
	public String inativarAtivar(@PathVariable int id){
		
		Cliente cliente = clienteServices.findById(id);
		
		if (cliente.isAtivo()) {
			cliente.setAtivo(false);
		}else {
			cliente.setAtivo(true);
		}
		
		clienteServices.update(cliente);
		
		return REDIRECT_LISTAR;
	}
	
	
	@RequestMapping(value = "/find")
	public String findCliente(String q){
		
		System.out.println(q);
		
		return REDIRECT_LISTAR;
	}
		
}
